package com.ruoyi.common.utils;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.ruoyi.common.exception.CustomException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *
 *  storm 远程调用脚本..
 * @author chenwen
 *
 */
public class ShellRPC {

    private static Connection conn;
    /** 远程机器host */
    private static String host;
    /** 用户名 */
    private static String userName;
    /** 密码 */
    private static String password;
    private static String charset = Charset.defaultCharset().toString();

    private static final int TIME_OUT = 1000 * 5 * 60;



    /**
     * 登录
     * @return
     * @throws IOException
     */
    private static boolean getConnection(String username, String password, String host) throws IOException {
        host = host;
        userName = username;
        password = password;

        conn = new Connection(host);
        conn.connect();
        return conn.authenticateWithPassword(userName, password);
    }

    /**
     * 执行脚本
     *
     * @param cmds
     * @return
     * @throws Exception
     */
    public static String exec(String cmds,String username, String password, String host) throws Exception {
        String outStr = "";
        String outErr = "";
        int ret = -1;
        try {
            if (getConnection(username,password,host)) {
                // Open a new {@link Session} on this connection
                Session session = conn.openSession();
                // Execute a command on the remote machine.
                session.execCommand(cmds);
                outStr = processStdout(session.getStdout(), charset);
                outErr = processStdout(session.getStderr(), charset);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                ret = session.getExitStatus();
            } else {
                throw new CustomException("登录远程机器失败" + host); // 自定义异常类 实现略
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("远程连接服务器执行脚本异常：" + e.getMessage());
        }finally {
            if (conn != null) {
                conn.close();
            }
        }
        return outStr+outErr;
    }

    /**
     * @param in
     * @param charset
     * @return
     * @throws Exception
     */
    private static String processStream(InputStream in, String charset) throws Exception {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
        return sb.toString();
    }

    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line).append("；\n");
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
    public static void main(String[] args) throws Exception {
       /* ShellRPC.exec("ls&&cat 1.txt","root","Ni7ehostr","193.168.0.203");*/

    }

}
